if (-not $PROFILE) {
    'Cannot find environment variable PROFILE'
    return
}

$targetDire = Split-Path -Parent $PROFILE
if (-not (Test-Path -PathType Container $targetDire)) {
    "Creating profile directory: $targetDire"
    mkdir $targetDire > $null
}

$baseUri = 'https://raw.gitcode.com/jamesfancy/pwsh-profiles/raw/profile'

function GetFileList {
    # expire on 2027-02-28
    $key = 'm1-eUSAPtc_C9AP1_6jMUif8'
    $url = 'https://api.gitcode.com/api/v5/repos/jamesfancy/pwsh-profiles/file_list?ref_name=profile'
    $headers = @{ 'Authorization' = "Bearer $key" }

    Invoke-RestMethod $url -ContentType "application/json" -Headers $headers
}

GetFileList | ForEach-Object { $_ } | Where-Object {
    $_ -ne ".gitignore"
} | ForEach-Object {
    $url = "$baseUri/$_"
    $target = Join-Path -Path $targetDire -ChildPath $_
    $parent = Split-Path -Parent $target
    if (-not (Test-Path -PathType Container $parent)) {
        "Creating directory: $parent"
        mkdir $parent -ErrorAction SilentlyContinue > $null
    }
    "Download $url => $target"
    Invoke-RestMethod -Uri $url -OutFile $target
}
